import Http from '@/service/Http';

export default class WeixinServlet {
    public dependent: boolean = false;
    public apiList: string[] = [];
    public configUrl: string = '';
    private defaultApiList: string[] = ['updateAppMessageShareData', 'updateTimelineShareData'];

    public constructor(apiList: string[] = [], configUrl: string = '') {
        const concatApiList: string[] = [...this.defaultApiList, ...apiList];
        this.configUrl = configUrl;
        this.apiList = Array.from(new Set(concatApiList));
        if (typeof (wx) !== 'undefined') {
            this.dependent = true;
            this.init();
        }
    }

    private async init(): Promise<any> {
        const res = await Http.get(this.configUrl, {url: location.origin + location.pathname});
        if (res.code === 1) {
            const signPackage = res.data.signPackage;
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: signPackage.appId, // 必填，公众号的唯一标识
                timestamp: signPackage.timestamp, // 必填，生成签名的时间戳
                nonceStr: signPackage.nonceStr, // 必填，生成签名的随机串
                signature: signPackage.signature, // 必填，签名，见附录1
                jsApiList: this.apiList, // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(() => {
                // tslint:disable-next-line:no-console
                console.log(2222);
            });
            wx.error((res: string) => {
                // tslint:disable-next-line:no-console
                console.log(res);
            });
        }

    }
}

declare let wx: any;
